var express = require('express');
const user = require(".././models/user")
const { success, fail, pagination } = require("../util/request_result")
const { Op } = require("sequelize")
var router = express.Router();
/* GET users listing. */
//获取全部用户
router.get('/', async function (req, res, next) {
  try {
    const { limit, offset } = pagination(req)
    let where = {}
    let name = req.query.name
    let sex = req.query.sex
    const condition = {
      order: [["id", "DESC"]],
      limit,
      offset,
    }
    if (name) {
      where.name = {
        [Op.like]: `%${name}%`
      }
    }
    if (sex) {
      where.sex = {
        [Op.like]: `%${sex}%`
      }
    }
    condition.where = where
    console.log('----------', where);
    const data = await user.findAndCountAll(condition)
    success(res, "查找成功", data, 200)
  } catch (err) {
    fail(res, "服务器异常", 500)
  }
});
//获取单个用户
router.get('/:id', async function (req, res, next) {
  try {
    const id = getId(req)
    console.log('id', id);
    const data = await user.findByPk(id)
    success(res, "查找成功", data, 200)
  } catch (err) {
    fail(res, "服务器异常", 500)
    throw err
  }
});
//添加用户
router.post('/add', async function (req, res, next) {
  try {
    const body = {
      name: req.body.name,
      sex: req.body.sex
    }
    const data = await user.create(body)
    success(res, "添加成功", data, 201)
  } catch (err) {
    fail(res, "服务器异常", 500)
  }

});
//修改用户
router.put('/:id', async function (req, res, next) {
  try {
    const id = getId(req)
    const body = {
      name: req.body.name,
      sex: req.body.sex
    }
    const data = await user.findByPk(id)
    const data_ = await data.update(body)
    success(res, "修改成功", data, 200)
  } catch (err) {
    fail(res, "服务器异常", 500)
  }

});
//删除用户
router.delete('/:id', async function (req, res, next) {
  try {
    const id = getId(req)
    const data = await user.findByPk(id)
    const data_ = data.destroy()
    success(res, "删除成功", data_, 200)
  } catch (err) {
    fail(res, "服务器异常", 500)
  }

});

function getId(req) {
  const { id } = req.params
  return id
}
module.exports = router;
